<template>
	<div class="chat-main-body">
		<div class="chat-main-body-element-box">
			<el-container style="height: 850px;">
				<!-- 左边导航栏 -->
				<el-aside class="left-istorical-contact-list-box">

					<!-- 左侧聊天好友列表 -->
					<el-menu class="left-istorical-contact-list-box-el-menu-box" background-color="Transparent">
						<el-menu-item
							@click="loadChatRecord(contacts.unread_quantity,contacts.ID,contacts.head_portrait,contacts.type,contacts.nick_name,contacts.sender_id,contacts.recipient_id)"
							v-for="(contacts,index) in contactsList" :key="index">
							<div class="contactsList-head-portrait">
								<el-avatar icon="el-icon-user-solid" :src="contacts.head_portrait">
								</el-avatar>
							</div>
							<div class="contactsList-nick-name">
								<span>
									{{contacts.nick_name}}
								</span>
							</div>
							<div class="contactsList-send-time">
								<span>{{contacts.send_time}}</span>
							</div>


							<div class="contactsList-message-content">
								<span>
									{{contacts.message_content}}
								</span>

							</div>
							<div class="contactsList-unread-quantity"
								:class="'contactsList-message-prompt-'+contacts.ID"
								v-show="contacts.unread_quantity!==0">
								<el-badge :value="contacts.unread_quantity" class="item">
									<span></span>
								</el-badge>
							</div>
						</el-menu-item>
					</el-menu>


					<!-- 左侧聊天好友列表分页 -->
					<div class="left-chat-friend-list-page-box">
						<el-pagination class="left-chat-friend-list-page-box-el-pagination" :page-size="13"
							:pager-count="11" :page-count="contactsListPage.pageCount" layout="prev, pager, next"
							:total="contactsListPage.total" @current-change="handleChatFriendListPage">

						</el-pagination>
					</div>


				</el-aside>


				<div class="call-back-home-icon-box">
					<el-tooltip class="item star" effect="light" content="返回主页" placement="top">
						<i class="el-icon-cloudy-and-sunny  star" @click="callBackHome"></i>
					</el-tooltip>
				</div>
				<!-- 左上角部分 -->
				<el-container>
					<el-header class="top-el-header" style="height: 45px;">
						<el-tooltip class="item star" effect="light" :content="userInfo.nickName" placement="left">
							<span @click="loadContactPoPUpBox()">
								<el-avatar icon="el-icon-user-solid" :src="userInfo.avatarLink"></el-avatar>
							</span>
						</el-tooltip>
						<!-- 添加好友图标 -->

						<div style="width: 30px;margin-top: -15%; margin-left: 34%;">
							<i class="el-icon-s-custom add-contact-icon" style="padding-left: 0px;"
								@click="dialogFormVisible = true"></i>
						</div>


						<!-- 创建群聊图标 -->
						<div style="width: 30px;margin-top: -11%; margin-left: 65%;">
							<i class="el-icon-circle-plus-outline create-group-chat-icon" style="padding-left: 0px;"
								@click="dialogGroupFormVisible = true"></i>
						</div>



						<!-- 添加好友弹框 -->
						<el-dialog title="添加好友" width="25%" :visible.sync="dialogFormVisible">
							<el-form>

								<el-form-item label="添加好友/加入群聊" label-width="150px">
									<el-switch v-model="operation">
									</el-switch>
								</el-form-item>

								<el-form-item label="用户昵称" :label-width="formLabelWidth" v-show="operation">
									<el-select v-model="value" clearable filterable remote reserve-keyword
										placeholder="请输入用户昵称" :remote-method="remoteMethod" :loading="loading">
										<el-option v-for="item in options" :key="item.id" :label="item.nickName"
											:value="item.id">
										</el-option>
									</el-select>
								</el-form-item>

								<el-form-item label="群号" :label-width="formLabelWidth" v-show="!operation">
									<!-- 添加群聊的输入框 -->


									<el-input type="text" placeholder="请输入群号" v-model="joinedGroupNumber" maxlength="19"
									 show-word-limit />

								</el-form-item>





							</el-form>
							<div slot="footer" class="dialog-footer">
								<el-button @click="dialogFormVisible = false">取 消</el-button>
								<el-button type="primary" @click="addContact()">确 定</el-button>
							</div>
						</el-dialog>


						<!-- 添加群聊弹框 -->
						<el-dialog title="创建群聊" width="25%" :visible.sync="dialogGroupFormVisible">
							<el-form :model="form">
								<el-form-item label="群聊名称" :label-width="formLabelWidth">
									<el-input v-model="form.groupName" autocomplete="off"></el-input>
								</el-form-item>
								<el-form-item label="群聊头像" :label-width="formLabelWidth">
									<el-upload class="avatar-uploader" action="#" :http-request="uploadGroupImg"
										:before-upload="beforeAvatarUpload">
										<img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
										<i v-else class="el-icon-plus avatar-uploader-icon"></i>
									</el-upload>
								</el-form-item>
							</el-form>
							<div slot="footer" class="dialog-footer">
								<el-button @click="dialogGroupFormVisible = false">取 消</el-button>
								<el-button type="primary" @click="createGroupChat()">确 定</el-button>
							</div>
						</el-dialog>



						<!-- 点击头像展示的弹框 -->
						<el-dialog title="联系人" width="30%" :visible.sync="dialogHeadPortraitVisible">
							<div class="head-frame-box">
								<div class="head-frame-box-top">
									<el-tabs @tab-click="handleClick" v-model="tabsName" :stretch="true">
										<el-tab-pane label="我的好友" name="MyFriends">
											<div class="head-frame-box-top-my-friends-list"
												v-for="(user,index) in friedsList" :key="index">
												<div class="my-friends-list-avatar">
													<el-avatar icon="el-icon-user-solid" :src="user.avatar_link">
													</el-avatar>
												</div>
												<div class="my-friends-list-user-name">{{user.nick_name}}</div>

												<div
													:class="[user.start==1?'my-friends-list-on-line-start':'my-friends-list-off-line-start']">
													{{user.start==1?"在线":"离线"}}
												</div>

												<hr />
											</div>

										</el-tab-pane>
										<el-tab-pane label="我加入群聊" name="IJoinTheGroupChat">
											<div class="head-frame-box-top-IJoinTheGroupChat-list"
												v-for="(group,index) in groupList" :key="index">
												<div class="IJoinTheGroupChat-list-avatar">
													<el-avatar icon="el-icon-user-solid" :src="group.group_avatar_img">
													</el-avatar>
												</div>
												<div class="IJoinTheGroupChat-list-user-name">{{group.group_name}}</div>
												<div class="IJoinTheGroupChat-list-group-number">
													<span style="color: #333;">群号:</span>
													{{group.group_number}}
												</div>
												<hr />
											</div>
										</el-tab-pane>
										<el-tab-pane label="我创建的群聊" name="GroupChatICreated">
											<div class="head-frame-box-top-GroupChatICreated-list"
												v-for="(group,index) in myCreateGroupList" :key="index">
												<div class="GroupChatICreated-list-avatar">
													<el-avatar icon="el-icon-user-solid" :src="group.group_avatar_img">
													</el-avatar>
												</div>
												<div class="GroupChatICreated-list-user-name">{{group.group_name}}</div>
												<div class="GroupChatICreated-list-group-number">
													<span style="color: #333;">群号:</span>
													{{group.group_number}}
												</div>
												<hr class="GroupChatICreated-list-hr" />
											</div>
										</el-tab-pane>
									</el-tabs>
								</div>
								<!-- 弹框分页 -->
								<div slot="footer" class="bottom-tip">
									<el-pagination :hide-on-single-page="true" :page-size="8" :pager-count="11"
										:current-page.sync="bulletFrame.currentPage" :page-count="bulletFrame.pageCount"
										layout="prev, pager, next" :total="bulletFrame.total"
										@current-change="handleCurrentChange">
									</el-pagination>
								</div>
							</div>

						</el-dialog>

					</el-header>

					<!-- 右边部分 -->
					<el-main class="chat-box-right">
						<div class="box-right" v-show="showChatRecord">

							<div class="recvfrom">
								<div class="nav-top">
									<span class="friend-nickname">{{friendNickname}}</span>
								</div>
								<div class="news-top" @scroll="monitorScrool" ref="leftChatFriendList">

									<ul>

										<li v-for="(chatRecord,index) in chatRecordList" :key="index"
											:class="[chatRecord.is_the_sender==1?'self':'other']">
											<div v-show="(chatRecord.type==1&&chatRecord.is_initialization_content==1&&chatRecord.sender_id==userInfo.ID)||(chatRecord.type==0&&chatRecord.is_initialization_content==1)"
												class="initialization-content-box">
												{{chatRecord.message_content}}
											</div>
											<div class="avatar" v-show="chatRecord.is_initialization_content!=1">
												<p v-show="chatRecord.type==1&&chatRecord.sender_id!==userInfo.ID">
													{{chatRecord.sender_nick_name}}</p>
												<img :src="chatRecord.sender_avatar_link" alt="">
											</div>
											<div :class="[chatRecord.type==1&&chatRecord.sender_id!==userInfo.ID?'msg':'my_msg']"
												v-show="chatRecord.is_initialization_content!=1">

												<p class="msg-text">{{chatRecord.message_content}} <span
														class="pizza"></span>
												</p>
												<span>{{chatRecord.send_time}}</span>
											</div>
										</li>



									</ul>
								</div>
							</div>


							<div class="sendto">

								<div class="but-text">
									<textarea name="" id="" cols="110" rows="6" v-model="messageObj.messageContent"
										@keyup.enter.exact="sendMessageContent" @keyup.ctrl.enter='lineFeed'></textarea>
									<el-button class="button" type="primary" round @click="sendMessageContent()">发送
									</el-button>
								</div>


							</div>
						</div>

						<div class="prompt-click-contact-box" v-show="!showChatRecord">
							您还未选中或发起聊天，快去跟好友聊一聊吧
						</div>
					</el-main>
				</el-container>
			</el-container>
		</div>
	</div>
</template>
<script>
	import {
		devChatManagementUrl
	} from '@/api/apiconst'
	import jwtDecode from 'jwt-decode';
	import {
		devUserManagementUrl
	} from '@/api/apiconst'
	import {
		devArticleManagementUrl
	} from '@/api/apiconst'

	export default {
		name: "Chat",
		data() {
			return {
				//用户信息
				userInfo: {
					ID: '',
					nickName: '',
					avatarLink: ''
				},
				//是否展示聊天记录
				showChatRecord: false,
				//聊天好友昵称
				friendNickname: "",
				//好友头像
				friendPortrait: "",
				//聊天记录列表
				chatRecordList: [],
				//聊天记录分页对象
				chatRecordListPage: {
					senderId: '',
					recipientId: '',
					//总页数
					pageCount: 0,
					//总记录条数
					total: 0,
					//页码
					page: 1,
					//单页展示条数
					size: 13
				},
				//聊天记录窗口初始化高度
				oldScrollHeight: 0,
				//会话列表
				contactsList: [],
				//会话列表分页对象
				contactsListPage: {
					//总页数
					pageCount: 0,
					//总记录条数
					total: 0,
					//页码
					page: 1,
					//单页展示条数
					size: 13
				},
				//是否展示添加好友弹框
				dialogFormVisible: false,
				//搜索好友的框渲染数据
				options: [],
				//选中的好友昵称
				value: '',
				//是否正在搜索好友
				loading: false,
				//展示添加群聊input框开关
				operation: true,
				//即将加入的群号
				joinedGroupNumber: null,
				//是否展示创建群聊弹框
				dialogGroupFormVisible: false,
				//群聊弹框填写的数据
				form: {
					//群聊名称
					groupName: '',
					//群聊头像
					imageUrl: ''
				},
				//群聊弹框标签的宽度
				formLabelWidth: '120px',
				//是否展示头像弹框
				dialogHeadPortraitVisible: false,
				//头像弹框导航名称
				tabsName: "MyFriends",
				friedsList: [],
				groupList: [],
				myCreateGroupList: [],
				//点击头像弹框分页参数
				bulletFrame: {
					//当前选中的标签名称  
					oldClickName: 'MyFriends',
					//当前页码
					currentPage: 1,
					//总页数
					pageCount: 0,
					//总记录条数
					total: 0,
					//页码
					page: 1,
					//单页展示条数
					size: 8
				},
				//发送的消息内容对象
				messageObj: {
					senderId: {
						ID: jwtDecode(localStorage.getItem("token")).ID,
						nickName: '',
						avatarLink: ''
					},
					recipientId: '',
					messageContent: '',
					readStatus: 0,
					type: 0,
					isInitializationContent: 0

				},


			}
		},
		mounted() {
			//解析当前用户信息
			let userMsg = jwtDecode(localStorage.getItem("token"));
			this.userInfo.ID = userMsg.ID;
			this.userInfo.nickName = userMsg.nickName;
			this.userInfo.avatarLink = userMsg.avatarLink;
			//设置当前消息发送者信息
			this.messageObj.senderId.ID = this.userInfo.ID;
			this.messageObj.senderId.nickName = this.userInfo.nickName;
			this.messageObj.senderId.avatarLink = this.userInfo.avatarLink;
			//加载会话列表
			this.loadSessionList(this.contactsListPage.page);
		},
		/**
		 * 监听发送过来的聊天消息
		 */
		watch: {
			'$store.state.chatMessageStr'(newVal, oldVal) {
				//获取消息对象
				let message = JSON.parse(newVal);

				let megItem = {
					is_the_sender: 0,
					is_initialization_content: message.isInitializationContent,
					message_content: message.messageContent,
					type: message.type,
					sender_id: message.senderId.ID,
					sender_nick_name: message.senderId.nickName,
					sender_avatar_link: message.senderId.avatarLink,
					send_time: this.$moment(message.sendTime).format("YYYY-MM-DD HH:mm:ss")
				}

				console.log("新增数据", megItem);




				//将数据添加到数组
				this.chatRecordList.push(megItem);

				console.log("新的消息列表", this.chatRecordList);



				// 让聊天记录的滚动条始终在最底部
				this.$nextTick(() => {
					this.$refs.leftChatFriendList.scrollTop = this.oldScrollHeight + 1400;
				})


				//设置会话列表数据
				let newContacts = {
					ID: message.ID,
					head_portrait: message.senderId.avatarLink,
					message_content: message.messageContent,
					nick_name: message.senderId.nickName,
					read_status: message.readStatus,
					recipient_id: message.recipientId,
					send_time: this.$moment(message.sendTime).format("YYYY-MM-DD HH:mm:ss"),
					sender_id: message.senderId.ID,
					type: message.type,
					unread_quantity: 1
				}

				let oldContactsList = this.contactsList;

				let _this = this;
				console.log("newContacts111111", newContacts);
				console.log("oldContactsList", oldContactsList);
				//遍历匹配原来的数据
				oldContactsList.forEach(function(item, index) {

					//判断当前的消息类型是否为私聊
					if (message.type == 0) {
						//判断新消息的发送者是不是旧消息的发送者
						if ((newContacts.sender_id == item.sender_id && newContacts.recipient_id == item
								.recipient_id) || (newContacts.sender_id == item.recipient_id && newContacts
								.recipient_id == item.sender_id)) {
							newContacts.head_portrait = item.head_portrait;
							newContacts.nick_name = item.nick_name;

							//判断当前接收到的这条新消息是不是，现在打开的聊天窗口中的接受者，即，有没有打开和当前消息发送者对应的聊天记录窗口
							if (newContacts.sender_id == _this.chatRecordListPage.recipientId) {
								newContacts.unread_quantity = 0;
								//将当前消息的状态修改为已读
								_this.updateChatRecordReadStatus(message.type, _this.chatRecordListPage.senderId,_this.chatRecordListPage.recipientId);

							} else {
								newContacts.unread_quantity = ++item.unread_quantity;
							}


							//移除当前元素
							oldContactsList.splice(index, 1);
						}

						//判断当前的消息类型是否为群聊	
					} else if (message.type == 1) {
						console.log("item2--------->");
						if (newContacts.recipient_id == item.recipient_id) {
							newContacts.head_portrait = item.head_portrait;
							newContacts.nick_name = item.nick_name;
							console.log("item2--------->",_this.chatRecordListPage.recipientId);
							//判断当前接收到的这条新消息是不是，现在打开的聊天窗口中的接受者，即，有没有打开和当前消息发送者对应的聊天记录窗口
							if (newContacts.recipient_id == _this.chatRecordListPage.recipientId) {
								newContacts.unread_quantity = 0;
								//将当前消息的状态修改为已读
								_this.updateChatRecordReadStatus(message.type, _this.chatRecordListPage.senderId,_this.chatRecordListPage.recipientId);

							} else {
								newContacts.unread_quantity = ++item.unread_quantity;
							}


							//移除当前元素
							oldContactsList.splice(index, 1);
						}

					}


				})

				oldContactsList.unshift(newContacts);
				this.contactsList = oldContactsList;


			}
		},

		methods: {
			/**
			 * 将消息文本域的的回车替换为发送
			 */
			lineFeed() {
				this.messageObj.messageContent = this.messageObj.messageContent + '\n'
			},
			/**
			 * 发送消息
			 */
			sendMessageContent() {
				//验证消息内容
				if (this.messageObj.messageContent == null || this.messageObj.messageContent == '') {
					this.$message.error("消息内容不能为空");
					return;
				}

				console.log("本次要发送的消息是", this.messageObj);
				//发送消息
				this.$websocket.Send(this.messageObj);

				//本次发送的数据，用于本地渲染
				let megItem = {
					is_the_sender: 1,
					sender_avatar_link: jwtDecode(localStorage.getItem("token")).avatarLink,
					message_content: this.messageObj.messageContent,
					send_time: "刚刚"
				}
				//将数据添加到数组
				this.chatRecordList.push(megItem);

				console.log("新的消息列表", this.chatRecordList);

				//清空文本域内容
				this.messageObj.messageContent = '';




				// 让滚动条始终在最底部
				this.$nextTick(() => {
					this.$refs.leftChatFriendList.scrollTop = this.oldScrollHeight + 1400;
				})



				//设置会话列表数据
				let newContacts = {
					ID: require('uuid').v1(),
					head_portrait: '',
					message_content: megItem.message_content,
					nick_name: '',
					read_status: 1,
					recipient_id: this.chatRecordListPage.recipientId,
					send_time: '刚刚',
					sender_id: this.chatRecordListPage.senderId,
					type: 0,
					unread_quantity: 0
				}


				let oldContactsList = this.contactsList;

				let _this = this;
				//遍历匹配原来的数据
				oldContactsList.forEach(function(item, index) {


					//判断当前的消息类型是否为私聊
					if (_this.messageObj.type == 0) {
						//判断新消息的发送者是不是旧消息的发送者
						if ((newContacts.sender_id == item.sender_id && newContacts.recipient_id == item
								.recipient_id) || (newContacts.sender_id == item.recipient_id && newContacts
								.recipient_id == item.sender_id)) {
							newContacts.head_portrait = item.head_portrait;
							newContacts.nick_name = item.nick_name;
							newContacts.type = item.type;

							//移除当前元素
							oldContactsList.splice(index, 1)

						}


						//判断当前的消息类型是否为群聊	
					} else if (_this.messageObj.type == 1) {
						console.log("item111--------->");
						if (newContacts.recipient_id == item.recipient_id) {
							newContacts.head_portrait = item.head_portrait;
							newContacts.nick_name = item.nick_name;
							newContacts.type = item.type;

							//移除当前元素
							oldContactsList.splice(index, 1)

						}

					}

				})

				oldContactsList.unshift(newContacts);
				this.contactsList = oldContactsList;


			},

			/**
			 * 左侧会话列表分页监听
			 * @param {Object} currentPage 当前页码
			 */
			handleChatFriendListPage(currentPage) {
				this.contactsListPage.page = currentPage;
				this.loadSessionList(currentPage);
			},

			/**
			 * 点击头像弹框导航切换
			 */
			handleClick(tab, event) {
				//判断防止重复点击
				if (tab.name === this.bulletFrame.oldClickName) {
					return;
				} else {
					this.bulletFrame.oldClickName = tab.name;
					this.bulletFrame.page = 1;
					this.bulletFrame.currentPage = 1;

					//判断当前点击的是否为我的好友
					if ("MyFriends" === tab.name) {
						//加载我的好友数据
						this.loadMyFriendsData(this.bulletFrame.page);
					} else if ("IJoinTheGroupChat" === tab.name) {
						//加载我加入的群聊
						this.loadTheDroupChatDataIJoined(this.bulletFrame.page);

					} else if ("GroupChatICreated" === tab.name) {
						//加载我创建的群聊
						this.loadTheGroupChatDataICreated(this.bulletFrame.page);
					}

				}



			},
			//点击头像加载弹框
			loadContactPoPUpBox() {
				this.dialogHeadPortraitVisible = true;
				//加载我的好友数据
				this.loadMyFriendsData(this.bulletFrame.page);
			},
			/**
			 * 监听分页按钮
			 * @param {Object} currentPage 单前页码
			 */
			handleCurrentChange(currentPage) {
				this.bulletFrame.page = currentPage;


				//判断当前点击的是否为我的好友
				if ("MyFriends" === this.bulletFrame.oldClickName) {
					//加载我的好友数据
					this.loadMyFriendsData(currentPage);

				} else if ("IJoinTheGroupChat" === this.bulletFrame.oldClickName) {
					//加载我加入的群聊
					this.loadTheDroupChatDataIJoined(currentPage);

				} else if ("GroupChatICreated" === this.bulletFrame.oldClickName) {
					//加载我创建的群聊
					this.loadTheGroupChatDataICreated(currentPage);
				}


			},
			/**加载我的好友数据
			 * @param {Object} loadPage 加载的页码
			 */
			loadMyFriendsData(loadPage) {
				this.$axios({
					url: '/chatRelated/queryFriends',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						page: loadPage,
						size: this.bulletFrame.size,
						userId: jwtDecode(localStorage.getItem("token")).ID
					}
				}).then(

					response => {
						if (response.data.code == 200) {
							const result = response.data.data;
							this.friedsList = result.records;
							this.bulletFrame.pageCount = result.pages;
							this.bulletFrame.total = result.total;

						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);
			},
			/**
			 * 加载我加入的群聊数据
			 * @param {Object} loadPage 加载的页码
			 */
			loadTheDroupChatDataIJoined(loadPage) {
				this.$axios({
					url: '/chatRelated/queryJoinGroup',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						page: loadPage,
						size: this.bulletFrame.size,
						userId: jwtDecode(localStorage.getItem("token")).ID
					}
				}).then(

					response => {
						if (response.data.code == 200) {
							const result = response.data.data;

							this.groupList = result.records;
							this.bulletFrame.pageCount = result.pages;
							this.bulletFrame.total = result.total;

						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);
			},
			/**
			 * 加载我创建的群聊数据
			 * @param {Object} loadPage 单前页码
			 */
			loadTheGroupChatDataICreated(loadPage) {
				this.$axios({
					url: '/chatRelated/queryCreateGroup',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						page: loadPage,
						size: this.bulletFrame.size,
						userId: jwtDecode(localStorage.getItem("token")).ID
					}
				}).then(

					response => {
						if (response.data.code == 200) {
							const result = response.data.data;
							this.myCreateGroupList = result.records;
							this.bulletFrame.pageCount = result.pages;
							this.bulletFrame.total = result.total;
						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);
			},
			/**
			 * 加载会话列表
			 * @param {Object} loadPage 当前页码
			 */
			loadSessionList(loadPage) {
				this.$axios({
					url: '/chatRelated/querySessionList',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						page: loadPage,
						size: this.contactsListPage.size,
						userId: jwtDecode(localStorage.getItem("token")).ID
					}
				}).then(

					response => {
						if (response.data.code == 200) {
							const result = response.data.data;

							this.contactsList = result.records;
							console.log("会话列表", this.contactsList);
							this.contactsListPage.pageCount = result.pages;
							this.contactsListPage.total = result.total;
						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);
			},

			/**
			 *  加载聊天记录
			 * @param {Object} type  当前消息类型
			 * @param {Object} loadPage  当前分页页码
			 * @param {Object} senderId   发送者ID
			 * @param {Object} recipientId 接收者ID
			 */
			async loadChatRecordList(type, loadPage, senderId, recipientId) {


				await this.$axios({
					url: '/chatRelated/queryChatRecordList',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						page: loadPage,
						size: this.chatRecordListPage.size,
						type: type,
						senderId: senderId,
						recipientId: recipientId
					}
				}).then(

					response => {

						if (response.data.code == 200) {
							const result = response.data.data;
							let dataList = result.records;

							let _this = this;
							dataList.forEach(function(item, index) {
								//将消息按照倒序的形式插入到数组当中
								_this.chatRecordList.unshift(item);
							})
							console.log("聊天记录：", this.chatRecordList);
							// 获取总页数
							this.chatRecordListPage.pageCount = result.pages;
							// 获取总记录数
							this.chatRecordListPage.total = result.total;
							// 当前页数累加
							++this.chatRecordListPage.page;

						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);
			},

			/**
			 * 添加好友
			 */
			addContact() {
				//判断当前是添加好友，还是添加群聊
				if (this.operation) {

					if (this.value == '' || this.value == null) {
						this.$message.error('用户昵称不能为空');
						return;
					}
					
					this.dialogFormVisible = false;

					this.$axios({
						method: 'POST',
						url: '/chatRelated/addFriend',
						baseURL: devChatManagementUrl,
						data: {
							userId: {
								ID: this.userInfo.ID
							},
							friendsId: {
								ID: this.value
							}
						}
					}).then(
						response => {

							if (response.data.code == 200) {

								// this.dialogFormVisible = false;
								this.$message.success("等待好友验证")
							} else {
								this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');
								// this.dialogFormVisible = true;
							}

						},
						error => {
							this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');

						}
					);
				} else {
					//添加群聊
					if (this.joinedGroupNumber > 0 && this.joinedGroupNumber != null) {
						
						this.dialogFormVisible = false;
							
						this.$axios({
							method: 'POST',
							url: '/chatRelated/joinGroupChat',
							baseURL: devChatManagementUrl,
							data: {
								userInformationId: this.userInfo.ID,
								nickName: this.userInfo.nickName,
								groupNumber: this.joinedGroupNumber
							}
						}).then(
							response => {

								if (response.data.code == 200) {

									// this.dialogFormVisible = false;
									this.$message.success("加入成功")
								} else if (response.data.code == 5006) {
									this.$message.error('当前群号不存在');
									// this.dialogFormVisible = true;
								}

							},
							error => {
								this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');

							}
						);

					} else {
						this.$message.error('群号不能为空');
					}


				}





			},
			/**
			 * 返回主页
			 */
			callBackHome() {
				//跳转主页
				this.$router.push({
					path: "/home"
				});
			},
			/**加载好友之间的聊天记录
			 * @param {Object} unreadQuantity 消息未读数量；
			 * @param {Object} messageID 消息记录ID；
			 * @param {Object} friendPortrait 好友头像；
			 * @param {Object} type 消息类型； 0- 私聊 1-群聊
			 * @param {Object} friendNickname 好友昵称
			 * @param {Object} senderId 发送者ID
			 * @param {Object} recipientId 接收者ID
			 */
			async loadChatRecord(unreadQuantity, messageID, friendPortrait, type, friendNickname, senderId, recipientId) {
				//展示聊天界面
				this.showChatRecord = true;
				//清空原有数据
				this.chatRecordList = [];
				this.chatRecordListPage.page = 1;
				//设置好友昵称
				this.friendNickname = friendNickname;
				//设置好友头像
				this.friendPortrait = friendPortrait;


				//设置消息发送时的用户ID

				const userID = jwtDecode(localStorage.getItem("token")).ID;
				//判断当前用户是否为发送者
				if (senderId != userID && senderId != '') {
					this.messageObj.recipientId = senderId;

					//设置本次加载的聊天用户ID
					this.chatRecordListPage.senderId = userID;
					this.chatRecordListPage.recipientId = senderId;


				}

				if (recipientId != userID && recipientId != '') {
					this.messageObj.recipientId = recipientId;

					//设置本次加载的聊天用户ID
					this.chatRecordListPage.senderId = userID;
					this.chatRecordListPage.recipientId = recipientId;

				}
				console.log("发送者", this.chatRecordListPage.senderId)
				console.log("接收者", this.chatRecordListPage.recipientId)
				//设置本次消息类型
				this.messageObj.type = type;

				console.log("type", this.messageObj.type)

				//判断是否有未读的消息
				if (unreadQuantity !== 0) {
					//设置消息提醒消失
					document.getElementsByClassName("contactsList-message-prompt-" + messageID)[0].style.display =
						"none";
					//修改消息读取状态
					this.updateChatRecordReadStatus(type, this.chatRecordListPage.senderId,this.chatRecordListPage.recipientId);
				}

				//加载聊天记录
				await this.loadChatRecordList(this.messageObj.type, this.chatRecordListPage.page, this
					.chatRecordListPage.senderId, this.chatRecordListPage.recipientId);

				//保存初始窗口高度
				this.oldScrollHeight = this.$refs.leftChatFriendList.scrollHeight;

				// 让滚动条始终在最底部
				this.$nextTick(() => {
					console.log(this.$refs.leftChatFriendList.scrollTop);
					console.log(this.$refs.leftChatFriendList.scrollHeight);
					this.$refs.leftChatFriendList.scrollTop = this.$refs.leftChatFriendList.scrollHeight - 700;
					console.log(this.$refs.leftChatFriendList.scrollTop);
				})


			},
			/**
			 * 监听聊天记录滚动条高度
			 */
			async monitorScrool(e) {
				//距离顶部的距离
				let height = this.$refs.leftChatFriendList.scrollTop;
				//可视高度
				let clientHeight = this.$refs.leftChatFriendList.clientHeight;
				//可滚动区域总高度
				let scrollHeight = this.$refs.leftChatFriendList.scrollHeight;
				//上一次可滚动区域的高度		
				let oldscrollHeight = this.$refs.leftChatFriendList.scrollHeight
				console.log("height", height)
				console.log("scrollHeight", scrollHeight)
				//判断是否触顶
				if (height == 0) {

					//判断是否还可以分页
					if (this.chatRecordListPage.page <= this.chatRecordListPage.pageCount) {
						//加载聊天记录
						await this.loadChatRecordList(this.messageObj.type, this.chatRecordListPage.page, this
							.chatRecordListPage.senderId,
							this.chatRecordListPage.recipientId);
						// 让滚动条始终在最底部
						this.$nextTick(() => {
							this.$refs.leftChatFriendList.scrollTop = this.$refs.leftChatFriendList
								.scrollHeight - oldscrollHeight;
						})

					} else {
						this.$message.success("没有更多了哦~");
						return;
					}
				}



			},
			/**
			 * 修改指定用户之间的消息读取状态
			 * @param {Object} senderId 发送者ID
			 * @param {Object} recipientId 接收者ID
			 */
			updateChatRecordReadStatus(type,senderId, recipientId) {
				this.$axios({
					method: 'POST',
					url: '/chatRelated/updateReadStatus',
					baseURL: devChatManagementUrl,
					data: {
						senderId:{
							ID:senderId
						},
						recipientId: recipientId,
						type:type
					}
				}).then(
					response => {

						if (response.data.code == 200) {
							console.log("修改成功");
						}

					},
					error => {
						this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');

					}
				);
			},
			/**
			 * 上传头像
			 * @param {Object} param 上传的文件
			 */
			uploadGroupImg(param) {

				const formdata = new FormData()
				formdata.append('file', param.file)
				formdata.append('remarks', "群聊头像")

				this.$axios({
					url: '/article/fileUpload',
					baseURL: devArticleManagementUrl,
					method: 'post',
					data: formdata,
					headers: {
						'Content-Type': 'multipart/form-data;charset=UTF-8',
					},
				}).then(
					response => {
						if (response.data.code == 200) {
							this.form.imageUrl = response.data.data;
						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				);

			},
			/**
			 * 创建群聊
			 */
			createGroupChat() {
				if (this.form.groupName == '' || this.form.groupName == null) {
					this.$message.error("群聊名称不能为空")
					return;
				}
				if (this.form.imageUrl == '' || this.form.imageUrl == null) {
					this.$message.error("群聊头像不能为空")
					return;
				}


				this.$axios({
					url: '/chatRelated/addGroup',
					baseURL: devChatManagementUrl,
					method: 'post',
					data: {
						groupName: this.form.groupName,
						groupAvatarImg: this.form.imageUrl,
						createUserId: {
							ID: jwtDecode(localStorage.getItem("token")).ID
						}
					}

				}).then(

					response => {
						if (response.data.code == 200) {
							this.dialogGroupFormVisible = false;
						} else {
							this.$message.error('诶呀~服务器走丢了,请稍后重试');
						}
					},
					error => {
						this.$message.error('诶呀~服务器走丢了');
					}
				)

			},
			//查询可添加的好友
			queryUserList() {
				console.log("开始搜索用户");
			},
			//搜素好友
			remoteMethod(query) {

				if (query !== '') {
					this.loading = true;



					//加载用户列表
					this.$axios({
						method: 'GET',
						url: '/user/list/' + query,
						baseURL: devUserManagementUrl,
					}).then(
						response => {

							if (response.data.code == 200) {

								this.options = response.data.data;


								this.loading = false;
							}


						},
						error => {
							this.$message.error('诶呀，服务器走丢了，稍后再来试试吧');
							//刷新图形验证码
							this.refreshCode();
						}
					);




				} else {
					this.options = [];
				}
			},
			/**验证文件格式
			 * @param {Object} file 文件
			 */
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			}

		}
	}
</script>

<style scoped>
	.initialization-content-box {
		position: absolute;
		left: 45%;
	}

	.contactsList-head-portrait {

		height: 10%;
		width: 10%;
	}

	.contactsList-nick-name {
		position: absolute;
		left: 24%;
		top: -26%;
		width: 20%;
		height: 70%;
		font-size: 15px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}


	.contactsList-send-time {
		position: absolute;
		left: 50%;
		top: -26%;
		width: 20%;
		height: 28%;
		color: #DCDFE6;
	}

	.contactsList-message-content {
		position: absolute;
		left: 24%;
		top: 20%;
		width: 50%;
		height: 70%;
		color: #909399;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.contactsList-unread-quantity {
		position: absolute;
		right: -39%;
		top: 20%;
		width: 50%;
		height: 70%;
	}


	.left-chat-friend-list-page-box {
		height: 4%;
		position: absolute;
		bottom: 2%;
		left: 5%;
	}


	.left-chat-friend-list-page-box-el-pagination>>>.btn-prev,
	.btn-next {
		background-color: Transparent;
		color: white;
	}

	.left-chat-friend-list-page-box-el-pagination>>>.el-pager li {
		background-color: Transparent;
		/* color:white; */
	}

	.left-chat-friend-list-page-box-el-pagination>>>.btn-next {
		background-color: Transparent;
		color: white;
	}


	.bottom-tip {
		position: absolute;
		bottom: 0;
	}

	.head-frame-box {
		width: 100%;
		height: 600px;
	}

	.head-frame-box-top {
		width: 100%;


	}

	.head-frame-box-top-my-friends-list {
		/* border: 1px solid red; */
	}

	.head-frame-box-top-IJoinTheGroupChat-list {}

	.my-friends-list-avatar {
		margin-left: 2%;
		width: -24%;
		width: 10%;
		height: 10%;
	}

	.IJoinTheGroupChat-list-avatar,
	.GroupChatICreated-list-avatar {
		margin-left: 2%;
		width: -24%;
		width: 10%;
		height: 10%;
	}

	.my-friends-list-user-name {

		margin-left: 13%;
		margin-top: -7%;
		min-width: 10%;
	}

	.IJoinTheGroupChat-list-user-name,
	.GroupChatICreated-list-user-name {
		margin-left: 13%;
		margin-top: -7%;
		min-width: 10%;
	}

	.IJoinTheGroupChat-list-group-number,
	.GroupChatICreated-list-group-number {
		margin-left: 13%;
		margin-top: 1%;
		color: #67C23A;
	}

	.my-friends-list-on-line-start {
		margin-left: 13%;
		margin-top: 1%;
		color: #67C23A;
	}

	.my-friends-list-off-line-start {
		margin-left: 13%;
		margin-top: 1%;
		color: #909399;
	}


	.chat-main-body {
		background: url("@/assets/images/chat-map.jpeg");
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-position: top center;
		background-attachment: fixed;
		overflow: auto;
		height: 100%;
		width: 100%;
		min-height: 100vh;
	}

	.chat-main-body-element-box {
		width: 80%;
		height: 80%;
		position: relative;
		left: 10%;
		margin-top: 2%;

	}

	.top-el-header {
		background-color: rgba(0, 0, 0, 0.5);
		color: #333;
		height: 1%;
		width: 24.6%;
		margin-left: -24.6%;


	}

	.call-back-home-icon-box {
		position: fixed;
		left: 4%;
		top: 50%;
		color: white;

		font-size: 34px;
	}

	.add-contact-icon {
		font-size: 30px;
		color: white;
		padding-left: 80px;
	}

	.create-group-chat-icon {
		font-size: 30px;
		color: white;
		padding-left: 60px;
	}

	.left-istorical-contact-list-box {
		background-color: rgba(0, 0, 0, 0.5);
		margin-top: 3%;
	}

	.left-istorical-contact-list-box-el-menu-box {
		background-color: rgba(0, 0, 0, 0.5);
		border-right: solid 0px #e6e6e6;

	}

	.left-istorical-contact-list-box-el-menu-box .el-menu-item {
		color: white;

	}



	.chat-box-right {
		margin-top: -45px;
		height: 10%;
	}

	.prompt-click-contact-box {
		color: white;
		position: absolute;
		left: 45%;
		top: 30%;
		font-size: 20px;
	}

	.box-right {
		float: left;
		width: 100%;
		height: 99%;
		margin-left: -20px;
		margin-top: -20px;
	}

	.box-right .recvfrom {
		width: 100%;
		height: 81%;
	}

	.box-right .recvfrom .nav-top {
		height: 45px;
		width: 100%;
		color: white;
	}

	.box-right .recvfrom .nav-top .friend-nickname {
		margin-left: 3%;
	}

	.box-right .recvfrom .nav-top p {
		line-height: 45px;
		font-size: 18px;
		font-weight: 600;
		margin-left: 25px;
	}

	.box-right .recvfrom .news-top {
		height: 100%;
		border-top: 1px solid #6C6C6C;
		border-bottom: 1px solid #6C6C6C;
		overflow-y: scroll;
		overflow-x: hidden;
		color: white;

	}

	::-webkit-scrollbar {
		display: none;
	}


	.box-right .recvfrom .news-top ul {
		height: 100%;
		width: 100%;
	}

	.box-right .recvfrom .news-top ul li {
		margin: 10px;
		min-height: 80px;
		position: relative;
		margin-top: 30px;
	}

	.box-right .recvfrom .news-top ul li .avatar img {
		height: 40px;
		width: 40px;
		border-radius: 50%;
	}

	.box-right .recvfrom .news-top ul li .msg {
		top: 45px;
		margin: 8px;
		min-height: 80px;
	}

	.box-right .recvfrom .news-top ul li .my_msg {
		top: -3px;
		margin: 8px;
		min-height: 80px;
	}

	.box-right .recvfrom .news-top ul li::after {
		clear: both;
		content: "";
		display: inline-block;
	}

	.box-right .recvfrom .news-top ul li .msg .msg-text {

		border-radius: 5px;
		padding: 8px;
		width: 350px;
		background-color: rgba(0, 0, 0, 0.3);
		margin: 0 auto;
		height: auto;
		word-break: break-all;
		/*只是强制换行，不管文字是否相同*/
	}

	.box-right .recvfrom .news-top ul li .my_msg .msg-text {

		border-radius: 5px;
		padding: 8px;
		width: 350px;
		background-color: rgba(0, 0, 0, 0.3);
		margin: 0 auto;
		height: auto;
		word-break: break-all;
		/*只是强制换行，不管文字是否相同*/
	}

	.box-right .recvfrom .news-top ul li .msg span {
		float: right;
		color: #C0C4CC;
	}

	.box-right .recvfrom .news-top ul li .my_msg span {
		float: right;
		color: #C0C4CC;
	}

	.box-right .recvfrom .news-top ul li.other .avatar {
		position: absolute;
		left: 0;
		top: 0;
	}

	.box-right .recvfrom .news-top ul li.other .msg {
		position: absolute;
		left: 50px;
	}

	.box-right .recvfrom .news-top ul li.other .my_msg {
		position: absolute;
		left: 50px;
	}

	.box-right .recvfrom .news-top ul {
		list-style-type: none;

	}

	.box-right .recvfrom .news-top ul li.self .avatar {
		position: absolute;
		right: 0;
		top: 0;
	}

	.box-right .recvfrom .news-top ul li.self .msg {
		position: absolute;
		right: 194px;
	}

	.box-right .recvfrom .news-top ul li.self .my_msg {
		position: absolute;
		right: 194px;
	}

	.box-right .sendto {
		width: 100%;
		height: 20%;


	}




	.box-right .sendto .but-text textarea {
		border: none;
		font-size: 22px;
		margin-left: 20px;
		width: 80%;
		height: 100px;
		background-color: rgba(0, 0, 0, 0.3);
		color: white;
	}

	.box-right .sendto .but-text {
		position: absolute;
		bottom: 1%;
	}

	.box-right .sendto .but-text .button {
		background-color: rgba(0, 0, 0, 0.3);
		padding: 5px 25px;
		border-color: white;
		position: absolute;
		right: 6%;
		bottom: 37%;
	}


	.avatar-uploader {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		width: 55%;
	}


	.avatar-uploader:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
